package ua.races.servlet;

import ua.races.command.ServletCommand;
import org.apache.log4j.Logger;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class MainServlet extends HttpServlet {

    private static final Logger log = Logger.getLogger(MainServlet.class.getName());
    private static Map<String, String> commands;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        log.info("init() complete");
        commands = (HashMap<String, String>) getServletContext().getAttribute("commands");

    }

    @Override
    public void destroy() {
        super.destroy();
        log.info("destroy() complete");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        log.info("MainServlet.doGet()");


        try {
            ((ServletCommand) Class.forName(commands.get(req.getRequestURI())).newInstance()).
                    execute(req, resp, getServletContext());
        } catch (InstantiationException e) {
            log.error(e);
        } catch (IllegalAccessException e) {
            log.error(e);
        } catch (ClassNotFoundException e) {
            log.error(e);
        } finally {
            log.info("doGet() method is done!");
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
           try {
            ((ServletCommand) Class.forName(commands.get(req.getRequestURI())).newInstance()).
                    execute(req, resp, getServletContext());
        } catch (InstantiationException e) {
            log.error(e);
        } catch (IllegalAccessException e) {
            log.error(e);
        } catch (ClassNotFoundException e) {
            log.error(e);
        } finally {
            log.info("doPost() method is done!");
        }

    }
}